﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace Vehicle_Maintenance
{
    public partial class Vehicle_Maintenance : Form
    {
        private Person activeUser = new Person();
        private Vehicle activeCar = new Vehicle();

        public Vehicle_Maintenance()
        {
            InitializeComponent();
        }

        private void Vehicle_Maintenance_Load(object sender, EventArgs e)
        {
            // TODO: This line of code loads data into the 'auto.Services' table. You can move, or remove it, as needed.
            this.servicesTableAdapter.Fill(this.auto.Services);
            bool succ = false;
            Change_User_or_Car dlg = new Change_User_or_Car();
            if ( dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK )
            {
                while ( !succ )
                {
                    try
                    {
                        activeUser.LoadByID( ( (ComboBox)dlg.Controls.Find( "cb_User", true )[ 0 ] ).SelectedValue.ToString() );
                        activeCar.LoadByVIN( ( (ComboBox)dlg.Controls.Find( "cb_Car", true )[ 0 ] ).SelectedValue.ToString() );
                        succ = true;

                        #region Fill in user Info
                        fillUserInfo();
                        #endregion
                        #region Fill in car info
                        fillCarInfo();
                        #endregion
                        #region Fill in Service DataGrid
                        fillServiceDG();
                        #endregion
                        #region Fill in Gas DataGrid
                        fillGasDG();
                        #endregion
                    }
                    catch
                    {
                        MessageBox.Show( "Failed to load user and car information." );
                    }
                }
            }
            else
            {
                Close();
            }

        }

        #region Change to different entities
        private void personToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Change_User_or_Car dlg = new Change_User_or_Car();
            bool succ = false;
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                while (!succ)
                {
                    try
                    {
                        activeUser.LoadByID(((ComboBox)dlg.Controls.Find("cb_User", true)[0]).SelectedValue.ToString());
                        activeCar.LoadByVIN(((ComboBox)dlg.Controls.Find("cb_Car", true)[0]).SelectedValue.ToString());
                        succ = true;

                        #region Fill in user Info
                        fillUserInfo();
                        #endregion
                        #region Fill in car info
                        fillCarInfo();
                        #endregion
                        dg_Service.RowCount = 0;
                        dg_Gas.RowCount = 0;
                        #region Fill in Service DataGrid
                        fillServiceDG();
                        #endregion
                        #region Fill in Gas DataGrid
                        fillGasDG();
                        #endregion
                    }
                    catch
                    {
                        MessageBox.Show("Failed to load user and car information.");
                    }
                }
            }
        }

        private void carToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Change_User_or_Car dlg = new Change_User_or_Car();
            bool succ = false;
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                while (!succ)
                {
                    try
                    {
                        activeUser.LoadByID(((ComboBox)dlg.Controls.Find("cb_User", true)[0]).SelectedValue.ToString());
                        activeCar.LoadByVIN(((ComboBox)dlg.Controls.Find("cb_Car", true)[0]).SelectedValue.ToString());
                        succ = true;

                        #region Fill in user Info
                        fillUserInfo();
                        #endregion
                        #region Fill in car info
                        fillCarInfo();
                        #endregion
                        dg_Service.RowCount = 0;
                        dg_Gas.RowCount = 0;
                        #region Fill in Service DataGrid
                        fillServiceDG();
                        #endregion
                        #region Fill in Gas DataGrid
                        fillGasDG();
                        #endregion
                    }
                    catch
                    {
                        MessageBox.Show("Failed to load user and car information.");
                    }
                }
            }
        }

        private void fillUserInfo()
        {
            l_Name.Text = activeUser.LastName + ", " + activeUser.FirstName;
            l_LicState.Text = activeUser.LicenseState;
            label20.Text = activeUser.LicenseNo;
        }

        private void fillCarInfo()
        {
            l_CName.Text = activeCar.Name;
            l_VIN.Text = activeCar.VIN;
            l_Make.Text = activeCar.Make;
            L_Model.Text = activeCar.Model;
            l_Year.Text = activeCar.Year;
            l_OrigOdom.Text = activeCar.Orig_Odom;
            l_CurrOdom.Text = activeCar.Curr_Odom;
            l_TCost.Text = activeCar.T_Spent;
            double mpg = Convert.ToDouble( activeCar.T_Gal );
            double miles = Convert.ToDouble( activeCar.Curr_Odom ) - Convert.ToDouble( activeCar.Orig_Odom );
            double Overall_mpg = miles / mpg;
            l_OverallMPG.Text = Overall_mpg.ToString();

            if ( activeCar.Varient != "" )
            {
                l_Varient.Text = activeCar.Varient;
            }
            else
            {
                l_Varient.Text = "";
            }
            if ( activeCar.Eng_Size != "" )
            {
                l_ESize.Text = activeCar.Eng_Size;
            }
            else
            {
                l_ESize.Text = "";
            }
            if ( activeCar.Tire_Size != "" )
            {
                l_TSize.Text = activeCar.Tire_Size;
            }
            else
            {
                l_TSize.Text = "";
            }
            if ( activeCar.Reg_Num != "" )
            {
                l_RegNum.Text = activeCar.Reg_Num;
            }
            else
            {
                l_RegNum.Text = "";
            }
            if ( activeCar.Tabs_Due != "" )
            {
                l_Tabs.Text = Convert.ToDateTime( activeCar.Tabs_Due ).ToShortDateString();
            }
            else
            {
                l_Tabs.Text = "";
            }
        }

        private void fillServiceDG()
        {
            DataTable Ser_Data = servicesTableAdapter.GetDataBySVIN( activeCar.VIN );
            DataTable SR_Data = serviceRemindersTableAdapter.GetDataBySRVIN( activeCar.VIN );
            foreach ( DataRow data in Ser_Data.Rows )
            {
                string milesL = "";
                string monthL = "";

                foreach ( DataRow SRdata in SR_Data.Rows )
                {

                    if ( ( SRdata[ "Date" ].ToString() == data[ "DateTime" ].ToString() ) && ( SRdata[ "Serv_Type" ].ToString() == data[ "Serv_Type" ].ToString() ) )
                    {
                        int month = Convert.ToInt32( SRdata[ "Months" ].ToString() );
                        DateTime ODate = Convert.ToDateTime( SRdata[ "Date" ].ToString() );
                        ODate = ODate.AddMonths( month );
                        TimeSpan months = ODate.Subtract( DateTime.Now );
                        double mileLeft = Convert.ToDouble( SRdata[ "Odom" ].ToString() ) - Convert.ToDouble( activeCar.Curr_Odom.ToString() );
                        milesL = mileLeft.ToString();
                        monthL = months.Days.ToString();
                        break;
                        //put date into grid
                    }
                }

                dg_Service.Rows.Add( data[ "DateTime" ], data[ "Serv_Type" ], milesL, monthL );

            }
        }

        private void fillGasDG()
        {
            DataTable G_data = this.gasFillUpsTableAdapter1.GetDataByGVIN( activeCar.VIN );
            foreach ( DataRow G_row in G_data.Rows )
            {
                double cost = Convert.ToDouble( G_row[ "Cost_Gal" ].ToString() );
                double gal = Convert.ToDouble( G_row[ "Gal" ].ToString() );
                double GTotal = cost * gal;

                double GMiles = Convert.ToDouble( G_row[ "Miles" ].ToString() );
                double GMPG = GMiles / gal;

                dg_Gas.Rows.Add( G_row[ "DateTime" ].ToString(),
                    G_row[ "Odom" ].ToString(), GMPG.ToString(), gal.ToString(), cost.ToString(), GTotal.ToString() );
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Close();
        } 
        #endregion

        #region Add new entities
        private void personToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            User dlg = new User();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                Person p = new Person();
                p.FirstName = ((TextBox)dlg.Controls.Find("tb_FName", true)[0]).Text;
                p.LastName = ((TextBox)dlg.Controls.Find("tb_LName", true)[0]).Text;
                string txt = ((ComboBox)dlg.Controls.Find("cb_State", true)[0]).Text;
                p.LicenseState = txt.Substring(txt.Length - 2);
                p.LicenseNo = ((TextBox)dlg.Controls.Find("tb_LicNum", true)[0]).Text;
                p.Insurrance = ((TextBox)dlg.Controls.Find("tb_Insur", true)[0]).Text;
                p.New();
            }
        }

        private void carToolStripMenuItem1_Click(object sender, EventArgs e)
        {
            Car dlg = new Car();
            if ( dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK )
            {
                Vehicle v = new Vehicle();
                v.VIN = ((TextBox)dlg.Controls.Find("tb_VIN", true)[0]).Text;
                v.Owner_ID = activeUser.ID;
                v.Year = ((NumericUpDown)dlg.Controls.Find("nud_Year", true)[0]).Value.ToString();
                v.Make = ((TextBox)dlg.Controls.Find("tb_Make", true)[0]).Text;
                v.Model = ((TextBox)dlg.Controls.Find("tb_Model", true)[0]).Text;
                v.Varient = ((TextBox)dlg.Controls.Find("tb_Varient", true)[0]).Text;
                v.T_Gal = "0";
                v.T_Spent = "0";
                v.Orig_Odom = ((TextBox)dlg.Controls.Find("tb_COdom", true)[0]).Text;
                v.Curr_Odom = ((TextBox)dlg.Controls.Find("tb_COdom", true)[0]).Text;
                v.Name = ((TextBox)dlg.Controls.Find("tb_Name", true)[0]).Text;
                v.Reg_Num = ((TextBox)dlg.Controls.Find("tb_RegNum", true)[0]).Text;
                v.Tire_Size = ((TextBox)dlg.Controls.Find("tb_TSize", true)[0]).Text;
                v.Eng_Size = ((TextBox)dlg.Controls.Find("tb_ESize", true)[0]).Text;
                v.Insur = ((TextBox)dlg.Controls.Find("tb_Insur", true)[0]).Text;
                v.New();
            }
        }

        private void gasToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Gas_Log dlg = new Gas_Log();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                FillUp f = new FillUp();
                f.VIN = activeCar.VIN;
                f.Date = ((DateTimePicker)dlg.Controls.Find("dt_GasDate", true)[0]).Value.ToString();
                f.Odom = ((TextBox)dlg.Controls.Find("tb_Odom", true)[0]).Text;
                f.CostGal = ((TextBox)dlg.Controls.Find("tb_COG", true)[0]).Text;
                f.Gal = ((TextBox)dlg.Controls.Find("tb_Gal", true)[0]).Text;
                if (((ComboBox)dlg.Controls.Find("cb_PayType", true)[0]).Text == "Other")
                {
                    f.PayType = ((TextBox)dlg.Controls.Find("tb_Other", true)[0]).Text;
                }
                else
                {
                    f.PayType = ((ComboBox)dlg.Controls.Find("cb_PayType", true)[0]).Text;
                }
                f.Loc = ((TextBox)dlg.Controls.Find("tb_Location", true)[0]).Text;
                f.GasBrand = ((TextBox)dlg.Controls.Find("tb_GasBrand", true)[0]).Text;
                double miles = Convert.ToDouble(f.Odom) - Convert.ToDouble(activeCar.Curr_Odom);
                f.Miles = miles.ToString();
                if (((RadioButton)dlg.Controls.Find("rb_Reg", true)[0]).Checked)
                {
                    f.Octane = "1";
                }
                else if (((RadioButton)dlg.Controls.Find("rb_MG", true)[0]).Checked)
                {
                    f.Octane = "2";
                }
                else if (((RadioButton)dlg.Controls.Find("rb_P", true)[0]).Checked)
                {
                    f.Octane = "3";
                }
                else
                {
                    f.Octane = "4";
                }

                DataTable carGal = vehiclesTableAdapter.GetDataByVIN(f.VIN);

                DataRow gal = carGal.Rows[0];

                double t_gal = Convert.ToDouble(gal["T_Gal"].ToString());
                t_gal += Convert.ToDouble(f.Gal);

                f.New(t_gal.ToString());

                #region Fill in Gas DataGrid
                dg_Gas.RowCount = 0;

                fillGasDG();
                #endregion

                // Update car info
                activeCar.Load();
                fillCarInfo();
            }
        }

        private void serviceToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Service_Log dlg = new Service_Log();
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string date = ((DateTimePicker)dlg.Controls.Find("dt_SerDate", true)[0]).Value.ToString();
                Service s = new Service();
                s.VIN = activeCar.VIN;
                s.Date = date;
                s.Cost = ((TextBox)dlg.Controls.Find("tb_Total", true)[0]).Text;
                s.Odom = ((TextBox)dlg.Controls.Find("tb_Odom", true)[0]).Text;
                s.Loc = ((TextBox)dlg.Controls.Find("tb_Loaction", true)[0]).Text;
                if (((ComboBox)dlg.Controls.Find("cb_PayType", true)[0]).Text == "Other")
                {
                    s.PayType = ((TextBox)dlg.Controls.Find("tb_POther", true)[0]).Text;
                }
                else
                {
                    s.PayType = ((ComboBox)dlg.Controls.Find("cb_PayType", true)[0]).Text;
                }
                if (((ComboBox)dlg.Controls.Find("cb_SerType", true)[0]).Text == "Other")
                {
                    s.SerType = ((TextBox)dlg.Controls.Find("tb_SOther", true)[0]).Text;
                }
                else
                {
                    s.SerType = ((ComboBox)dlg.Controls.Find("cb_SerType", true)[0]).Text;
                }
                if (((CheckBox)dlg.Controls.Find("chb_SerReminder", true)[0]).Checked)
                {
                    ServiceReminder sr = new ServiceReminder();
                    sr.VIN = activeCar.VIN;
                    sr.date = date;
                    string miles = ((TextBox)dlg.Controls.Find("tb_Miles", true)[0]).Text;
                    double srOdom = Convert.ToDouble(s.Odom) + Convert.ToDouble(miles);
                    sr.Odom = miles.ToString();
                    sr.Months = ((NumericUpDown)dlg.Controls.Find("num_Months", true)[0]).Value.ToString();

                    if (((ComboBox)dlg.Controls.Find("cb_SerType", true)[0]).Text == "Other")
                    {
                        sr.SerType = ((TextBox)dlg.Controls.Find("tb_SOther", true)[0]).Text;
                    }
                    else
                    {
                        sr.SerType = ((ComboBox)dlg.Controls.Find("cb_SerType", true)[0]).Text;
                    }
                    sr.New();
                }
                s.New();

                #region Fill in Service DataGrid
                dg_Service.RowCount = 0;

                fillServiceDG();
                #endregion

            }
        } 
        #endregion

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {

        }

        #region Update Gas, Service/ServiceReminder, and Car
        private void dg_Gas_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string GDate = "";
            string G_Odom = "";

            DataGridViewRow dataRow = dg_Gas.CurrentRow;
            G_Odom = dataRow.Cells["G_Odom"].Value.ToString();
            GDate = dataRow.Cells["G_Date"].Value.ToString();

            Gas_Log dlg = new Gas_Log(true, activeCar.VIN, GDate, G_Odom);
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //update a gas log
            }
        }

        private void dg_Service_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {

            string serDate = "";
            string serType = "";


            DataGridViewRow dataRow = dg_Service.CurrentRow;
            serType = dataRow.Cells["Service_Type"].Value.ToString();
            serDate = dataRow.Cells["S_Date"].Value.ToString();

            Service_Log dlg = new Service_Log(true, l_VIN.Text, serDate, serType);
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //update a service
            }
        }

        private void b_Update_Click(object sender, EventArgs e)
        {
            Car dlg = new Car(true, activeCar.VIN);
            if (dlg.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //update a car
                activeCar.Year = ( (NumericUpDown)dlg.Controls.Find( "nud_Year", true )[ 0 ] ).Value.ToString();
                activeCar.Make = ( (TextBox)dlg.Controls.Find( "tb_Make", true )[ 0 ] ).Text;
                activeCar.Model = ( (TextBox)dlg.Controls.Find( "tb_Model", true )[ 0 ] ).Text;
                activeCar.Varient = ( (TextBox)dlg.Controls.Find( "tb_Varient", true )[ 0 ] ).Text;
                activeCar.Name = ( (TextBox)dlg.Controls.Find( "tb_Name", true )[ 0 ] ).Text;
                activeCar.Reg_Num = ( (TextBox)dlg.Controls.Find( "tb_RegNum", true )[ 0 ] ).Text;
                activeCar.Tire_Size = ( (TextBox)dlg.Controls.Find( "tb_TSize", true )[ 0 ] ).Text;
                activeCar.Eng_Size = ( (TextBox)dlg.Controls.Find( "tb_ESize", true )[ 0 ] ).Text;
                activeCar.Insur = ( (TextBox)dlg.Controls.Find( "tb_Insur", true )[ 0 ] ).Text;
                activeCar.Update();
                fillCarInfo();
            }
        } 
        #endregion
    }
}
